const Koa = require('koa')
const bodyParser = require('koa-bodyparser');
const mongoose = require('mongoose')
const session = require('koa-session')
const cookie = require('koa-cookie')

const config = require('./config/config');
const log = require('./utils/log')
const controller = require('./controller');

mongoose.Promise = global.Promise;
var db = mongoose.connect(config.mongodb);

db.connection.on('error',(err)=>{
    log.error('mongodb connect error' ,err)
})
db.connection.once('open', () => {
    log.debug('mongodb is ready')
})


const app = new Koa();
app.use(bodyParser());
// app.use(cookie());

// const mysession = {
//   key: 'koa:sess', /** (string) cookie key (default is koa:sess) */
//   /** (number || 'session') maxAge in ms (default is 1 days) */
//   /** 'session' will result in a cookie that expires when session/browser is closed */
//   /** Warning: If a session cookie is stolen, this cookie will never expire */
//   maxAge: 86400000,
//   overwrite: true, /** (boolean) can overwrite or not (default true) */
//   httpOnly: true, /** (boolean) httpOnly or not (default true) */
//   signed: true, /** (boolean) signed or not (default true) */
// };
// app.use(session(mysession, app));
// // or if you prefer all default config, just use => app.use(session(app)); 
 
//log request URL
app.use(async (ctx,next)=>{
    console.log(`Process ${ctx.request.method} ${ctx.request.url}...`);
    await next();
})

//add router
app.use(controller());



app.listen(3000);
log.debug("app started at potr 3000")